package com.campus.config;

import com.campus.config.handler.AuthInterceptor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Configuration //继承WebMvcConfigurer接口
@EnableWebMvc
@ComponentScan(basePackages = "com.campus")
public class AuthInterceptorConfig implements WebMvcConfigurer {

    //    @Autowired
//    private AuthInterceptor jWTInterceptor;
//
//    public AuthInterceptor getjWTInterceptor() {
//        return jWTInterceptor;
//    }
//
//    public void setjWTInterceptor(AuthInterceptor jWTInterceptor) {
//        this.jWTInterceptor = jWTInterceptor;
//    }
//

//

    //视图解析器
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("redirect:/home");
    }
    //配置ResourceHandler访问静态资源
    //笔者此处是为了解决swagger-ui被莫名拦截的问题，无此问题的小伙伴可以跳过
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    // add message convertor
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        converter.setObjectMapper(objectMapper);
        List<MediaType> mediaTypes = new ArrayList<>();
        mediaTypes.add(MediaType.APPLICATION_JSON);
        converter.setSupportedMediaTypes(mediaTypes);
        converters.add(converter);
    }
    //添加登录拦截器、管理员拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AuthInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/student/exportStudents","/student/export")
                .excludePathPatterns("/sysUser/login","/swagger-ui.html/**","/doc.html","/webjars/**","/swagger-resources","/swagger-resources/**","/v2/**");
    }

}